package com.liu.lab04.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginValidationFilter", urlPatterns = {"/*"})
public class LoginValidationFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession();
        String reqURI = req.getRequestURI(); // 获取请求的 URI
        String user = (String) session.getAttribute("user");
        System.out.println(user);

        // 放行登录页面和错误页面
        if (reqURI.endsWith("/login.jsp") || reqURI.endsWith("/loginError.jsp") || reqURI.endsWith("/LoginServlet")) {
            chain.doFilter(request, response);
        } else {
            // 检查用户是否已登录
            if (user != null) {
                chain.doFilter(request, response);
            } else {
                resp.sendRedirect(req.getContextPath() + "/loginError.jsp");
                return;
            }
        }
    }
}